/*
 * @(#)GSProductInfoDownServlet.java   
 *
 * Project: CUPSecureBM
 * 
 * Modify Information:
 *  Author          Date                Description
 * ==============   =================   =====================
 *  yonggangguo     2005-12-29             Create this file
 *  Tuthmos Liu     2008-06-16           增加图件号
 * Copyright notice:
 *   Copyright (c) 2001-2005 Beijing HiTRUST Technology Co., Ltd.
 *   1808 Room, Science & Technology Building, No. 9 South Street,
 *   Zhong Guan Cun, Haidian District, Beijing ,100081, China
 *   All rights reserved.
 *
 *   This software is the confidential and proprietary information of
 *   HiTRUST.COM, Inc. ('Confidential Information').  You shall not
 *   disclose such Confidential Information and shall use it only in
 *   accordance with the terms of the license agreement you entered
 *   into with HiTRUST.
 */

package com.hitrust.gs.action;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import system.base.Product;
import system.base.ProductSearchEvent;
import system.base.ProductSearchTempEvent;
import system.base.Provider;
import system.base.User;
import system.base.WarehouseCategoryRelation;
import system.base.WarehouseCategoryRelationSearchEvent;

import com.hitrust.gs.dao.GSProductBidDao;
import com.hitrust.gs.dao.GSProductTypeDao;
import com.hitrust.gs.dao.GSProductTypeManagerDao;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;

import framework.core.Conditions;
import framework.core.DBConnection;
import framework.core.LogWriter;
import framework.core.ObjectList;
import framework.core.Value;

public class GSProductInfoDownServlet extends HttpServlet {

    public void init(ServletConfig aConfig) throws ServletException {
        super.init(aConfig);
    }
    private boolean isTel=false;//是否显示进价
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
       
        String type = (String)request.getParameter("type");
        HSSFWorkbook tWb=null;
        DBConnection dbcon = null;
        OutputStream tOutputStream = null;
        try {
            dbcon = DBConnection.open();
            User user = (User)request.getSession().getAttribute("User");
            if(user!=null&&user.getTel()!=null&&user.getTel().equals("1")){
            	isTel=true;
            }else{
            	isTel=false;
            }
            if(type==null||type.trim().equals("")){	
            	 if(request.getSession().getAttribute("ProductSearchEvent") instanceof ProductSearchEvent){
            		 ProductSearchEvent event = (ProductSearchEvent)request.getSession().getAttribute("ProductSearchEvent");
            		 ObjectList list = Product.fetch().search(dbcon, event.toConditions());
            		 tWb= writeExcel(list, null);
            	 }else if(request.getSession().getAttribute("ProductSearchEvent") instanceof ProductSearchTempEvent){
            		 ProductSearchTempEvent event = (ProductSearchTempEvent)request.getSession().getAttribute("ProductSearchEvent");
            		 ObjectList list = Product.fetch().search(dbcon, event.toConditions());
            		 tWb=writeExcel(list, null);
            	 }else{
            		 ProductSearchEvent event = (ProductSearchEvent)request.getSession().getAttribute("ProductSearchEvent");
            		 ObjectList list = Product.fetch().search(dbcon, event.toConditions());
            		 tWb= writeExcel(list, null);
            	 }
            	
            }else if(type!=null&&type.trim().equals("1")){
                WarehouseCategoryRelationSearchEvent wevent = (WarehouseCategoryRelationSearchEvent)request.getSession().getAttribute("WarehouseCategoryRelationEvent");
            	wevent.setPageSize( Value.NULL_INT );
                ObjectList list = WarehouseCategoryRelation.fetch().search(dbcon,wevent);           	
            	ObjectList ws = ObjectList.getList();
                for(int i=0;i<list.size();i++)
                {
                	WarehouseCategoryRelation obj = (WarehouseCategoryRelation)list.get(i);
                    Product pro = Product.fetchByConcentricityCode(dbcon,obj.getProductCode());
                    if(pro!=null){
                	ws.add(pro);
                    }else{
                    	LogWriter.error("导出EXCELL出错："+obj.getProductCode()+"没有这个产品");
                    }
                
                }
                tWb=writeExcel(ws, null);
            }
            if( tWb!=null){
            	 response.setContentType("application/excel;charset=UTF-16");
                 response.setHeader("Content-disposition", "attachment; filename=product.xls");
                 response.setHeader("Content-Description", "产品查询结果");
                 tOutputStream = response.getOutputStream();
            	tWb.write(tOutputStream);
            	tOutputStream.flush();
            	tOutputStream.close();
            	tWb=null;           	
           }
            
        } catch (Exception e) {
            GSLogWriter.error(e.getMessage());
		    e.printStackTrace();
        } finally {
            try {
                if (tOutputStream != null) {
                    tOutputStream.close();
                }
                System.gc();
        		Runtime.getRuntime().gc();
                dbcon.close();
                
            } catch (Exception e) {
            }
        }
        
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        doPost(request, response);
    }

    private HSSFWorkbook writeExcel(ObjectList aList, OutputStream tOutputStream)throws Exception  {
        DBConnection con = null;
        HSSFWorkbook tWb=null;
        try {
            if (GSBaseConstants.PLANPRICE.equals("true")) {
                con = DBConnection.open();
               tWb = new HSSFWorkbook();
                HSSFSheet tSheet = tWb.createSheet();
                tWb.setSheetName(0, "产品浏览", HSSFCell.ENCODING_UTF_16);
                HSSFRow tRow = tSheet.createRow((short) 0);
                createCell(tWb, tRow, (short) 0, "集中编码", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 1, "产品名称", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 2, "价格(元)", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 3, "计划价(元)", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 4, "规格", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 5, "型号", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 6, "质保期", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 7, "单位", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 8, "品牌", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 9, "生产厂商", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 10, "产地", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 11, "供应商", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 12, "图件号", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 13, "结算模式", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 14, "是否正式产品", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 15, "是否采购", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 16, "所属仓库", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 17, "创建时间", HSSFCellStyle.ALIGN_CENTER);
          
                for (int i = 0; i < aList.size(); i++) {
                    tRow = tSheet.createRow((short) (i + 1));
                    Product obj = (Product) aList.get(i);
                    createCell(tWb, tRow, (short) 0, obj.viewConcentricityCode(con));
                    createCell(tWb, tRow, (short) 1, obj.viewName(con));
                    createCell(tWb, tRow, (short) 2, obj.viewUnitPrice(con));
                    createCell(tWb, tRow, (short) 3, obj.viewPlanPrice(con));
                    createCell(tWb, tRow, (short) 4, obj.viewSpec(con));
                    createCell(tWb, tRow, (short) 5, obj.viewModel(con));
                    createCell(tWb, tRow, (short) 6, obj.viewQualityAssurePeriod(con));
                    createCell(tWb, tRow, (short) 7, obj.viewProductUnit(con));
                    createCell(tWb, tRow, (short) 8, obj.viewProductBrand(con));
                    createCell(tWb, tRow, (short) 9, obj.viewManufaturer(con));
                    createCell(tWb, tRow, (short) 10, obj.viewArea(con));
                    createCell(tWb, tRow, (short) 11, obj.viewProviderCode(con));
                    createCell(tWb, tRow, (short) 12, obj.viewDrawingPieceCode(con));
                    createCell(tWb, tRow, (short) 13, obj.viewBalanceMode(con));
                    createCell(tWb, tRow, (short) 14, obj.viewIsNormal(con));
                    createCell(tWb, tRow, (short) 15, obj.viewIsBuy(con));
                    createCell(tWb, tRow, (short) 16, obj.viewWarehouseName(con));
                    createCell(tWb, tRow, (short) 17, obj.viewCreateTime(con));
                }
                tWb.write(tOutputStream);
                tOutputStream.flush();
            } else {
                con = DBConnection.open();
                tWb = new HSSFWorkbook();
                HSSFSheet tSheet = tWb.createSheet();
                tWb.setSheetName(0, "产品浏览", HSSFCell.ENCODING_UTF_16);
                HSSFRow tRow = tSheet.createRow((short) 0);
                createCell(tWb, tRow, (short) 0, "种类编码", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 1, "集中编码", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 2, "产品名称", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 3, "供应商", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 4, "价格(元)", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 5, "单位", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 6, "是否采购", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 7, "结算模式", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 8, "型号", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 9, "规格", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 10, "质保期(天)", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 11, "质保期(公里)", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 12, "生产厂商", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 13, "产地", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 14, "品牌", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 15, "图件号", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 16, "附加属性", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 17, "创建时间", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 18, "区域", HSSFCellStyle.ALIGN_CENTER);
                createCell(tWb, tRow, (short) 19, "分类", HSSFCellStyle.ALIGN_CENTER);
                if(isTel){
                	createCell(tWb, tRow, (short) 20, "进价", HSSFCellStyle.ALIGN_CENTER);
                }
                GSProductTypeManagerDao dao =new GSProductTypeManagerDao();
            	Map typeMap=dao.findAllByTypeCodeAndPUpperCode("1000");
            	Map bidMap=dao.findAllByTypeCodeAndPUpperCode("2000");
            	 GSProductTypeDao typeDao2 =new GSProductTypeDao();
            	 //所有的产品区域数据
            	 Map typeMap2=typeDao2.findAllProductType();
            	 GSProductBidDao bidDao2 =new GSProductBidDao();
            	 //所有的产品区域数据
            	 Map bidMap2=bidDao2.findAllProductBid();
            	Map providerMap=new HashMap();
            	Conditions cs = new Conditions();
                ObjectList pro = Provider.fetch().search(con, cs);
                
                if(pro!=null&&pro.size() > 0){
                	for(int j=0;j<pro.size();j++){
                		Provider bean = (Provider)pro.get(j);
                		providerMap.put(bean.getCode(),bean.getName());
                	}
                }
                for (int i = 0; i < aList.size(); i++) {
                    tRow = tSheet.createRow((short) (i + 1));
                    Product obj = (Product) aList.get(i);
                    String providerName="";
                    if(providerMap.containsKey(obj.getProviderCode())){
                    	providerName=(String)providerMap.get(obj.getProviderCode());
                    }
                   String bidName=null;
                   String typeName="";
                   if(bidMap2.containsKey(obj.getConcentricityCode())){
                	   String productType=(String)bidMap2.get(obj.getConcentricityCode());
                	   bidName=(String)bidMap.get(productType);
                   }
                   if(typeMap2.containsKey(obj.getConcentricityCode())){
                	   String productType=(String)typeMap2.get(obj.getConcentricityCode());
                	   typeName=(String)typeMap.get(productType);
                   }
//                    GSProductTypeDao typeDao = new GSProductTypeDao();
//                    GSProductTypeBean bean = typeDao.findProductTypeByProuductCodeNoStauts(obj.getConcentricityCode().trim());
//                    GSProductBidDao bidDao = new GSProductBidDao();
//                    GSProductBidBean bidBean = bidDao.findProductBidByProuductCode(obj.getConcentricityCode().trim());
                    createCell(tWb, tRow, (short) 0, obj.getCategoryCode());
                    createCell(tWb, tRow, (short) 1, obj.viewConcentricityCode(con));
                    createCell(tWb, tRow, (short) 2, obj.viewName(con));
                    createCell(tWb, tRow, (short) 3, providerName);
                    createCell(tWb, tRow, (short) 4, obj.viewUnitPrice(con));
                    createCell(tWb, tRow, (short) 5, obj.viewProductUnit(con));
                    createCell(tWb, tRow, (short) 6, obj.viewIsBuy(con));
                    createCell(tWb, tRow, (short) 7, obj.viewBalanceMode(con));
                    createCell(tWb, tRow, (short) 8, obj.viewModel(con));
                    createCell(tWb, tRow, (short) 9, obj.viewSpec(con));
                    createCell(tWb, tRow, (short) 10, obj.viewQualityAssurePeriod(con));
                    createCell(tWb, tRow, (short) 11, obj.viewKmQualityAssurePeriod(con));
                    createCell(tWb, tRow, (short) 12, obj.viewManufaturer(con));
                    createCell(tWb, tRow, (short) 13, obj.viewArea(con));
                    createCell(tWb, tRow, (short) 14, obj.viewProductBrand(con));
                    createCell(tWb, tRow, (short) 15, obj.viewDrawingPieceCode(con));
                    createCell(tWb, tRow, (short) 16, obj.viewAppenderProperty(con));
                    createCell(tWb, tRow, (short) 17, obj.viewCreateTime(con));
                   //createCell(tWb, tRow, (short) 18, obj.viewCreateTime(con));

                    	 createCell(tWb, tRow, (short) 18, typeName);
                   if(bidName==null){
                	   bidName="";
                   }
                   createCell(tWb, tRow, (short) 19,bidName); 
                   if(isTel){
                	   createCell(tWb, tRow, (short) 20,obj.viewPlanPrice(con));   
                   }
               }
               
            	typeMap=null;
            	bidMap=null;
            	providerMap=null;
            	typeMap2=null;
            	bidMap2=null;
                System.gc();
        		Runtime.getRuntime().gc();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw  ex;
        } finally {
            try {
            	
            	if(con!=null){
            		con.close();
            	}               
            } catch (Exception e) {
            }
        }
        return tWb;
    }

    private void createCell(HSSFWorkbook aWb, HSSFRow aRow, short column, String aValue) {
        HSSFCell tCell = aRow.createCell(column);
        tCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        tCell.setCellValue(aValue);
    }

    private void createCell(HSSFWorkbook aWb, HSSFRow aRow, short column, String aValue, short aAlign) {
        HSSFCell tCell = aRow.createCell(column);
        tCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        tCell.setCellValue(aValue);
        HSSFCellStyle tCellStyle = aWb.createCellStyle();
        tCellStyle.setAlignment(aAlign);
        tCell.setCellStyle(tCellStyle);
    }
}
